package cn.tqfeiyang.springplus.system.security;

import cn.tqfeiyang.springplus.framework.security.AuthenticationUserDetails;
import cn.tqfeiyang.springplus.framework.security.AuthenticationUserLoader;
import cn.tqfeiyang.springplus.system.entity.RoleEntity;
import cn.tqfeiyang.springplus.system.entity.UserEntity;
import cn.tqfeiyang.springplus.system.mapper.UserMapper;
import cn.tqfeiyang.springplus.system.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MybatisAuthenticationUserLoader implements AuthenticationUserLoader {

    /**
     * 用户映射接口
     */
    @Resource
    private UserMapper userMapper;

    /**
     * 用户/角色关联接口
     */
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public AuthenticationUserDetails loadByUsername(String username) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getUsername, username);
        UserEntity userEntity = userMapper.selectOne(wrapper);
        return userEntity != null ? convertToUserDetails(userEntity) : null;
    }

    @Override
    public AuthenticationUserDetails loadByUUID(String uuid) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getUuid, uuid);
        UserEntity userEntity = userMapper.selectOne(wrapper);
        return userEntity != null ? convertToUserDetails(userEntity) : null;
    }

    private AuthenticationUserDetails convertToUserDetails(UserEntity userEntity) {
        AuthenticationUserDetails userDetails = new AuthenticationUserDetails();
        userDetails.setId(userEntity.getUserId());
        userDetails.setUsername(userEntity.getUsername());
        userDetails.setPassword(userEntity.getPassword());
        userDetails.setUuid(userDetails.getUuid());
        userDetails.setEnabled(userEntity.getEnabled());
        userDetails.setNickname(userEntity.getNickname());
        userDetails.setAvatar(userEntity.getAvatar());
        userDetails.setIntroduction(userEntity.getIntroduction());

        List<RoleEntity> roleList = userRoleMapper.selectRoleListByUserId(userEntity.getUserId());
        roleList.stream().forEach(roleEntity -> userDetails.getRoles().add(roleEntity.getCode()));

        return userDetails;
    }
}
